<template>
	<div class="system-menu-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px" :draggable="true">
			<el-form ref="menuDialogFormRef" :model="state.ruleForm" :rules="rules" size="default" label-width="80px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="上级菜单" prop="parentId">
							<el-cascader
								:options="state.menuData"
								:props="{ checkStrictly: true, value: 'id', label: 'title' }"
								placeholder="请选择上级菜单"
								clearable
								class="w100"
								v-model="state.ruleForm.parentId"
							>
								<template #default="{ node, data }">
									<span>{{ data.title }}</span>
									<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
								</template>
							</el-cascader>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="菜单标题" prop="menuTitle">
							<el-input v-model="state.ruleForm.menuTitle" placeholder="格式：message.router.xxx" clearable></el-input>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="菜单名称" prop="meta.title">
							<el-input v-model="state.ruleForm.meta.title" placeholder="格式：message.router.xxx" clearable></el-input>
						</el-form-item>
					</el-col>
					<!-- <template> -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="路由名称" prop="menuName">
							<el-input v-model="state.ruleForm.menuName" placeholder="路由中的 name 值" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="路由路径" prop="accessPath">
							<el-input v-model="state.ruleForm.accessPath" placeholder="路由中的 path 值" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="重定向" prop="redirect">
							<el-input v-model="state.ruleForm.redirect" placeholder="请输入路由重定向" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="菜单图标" prop="meta.icon">
							<IconSelector placeholder="请输入菜单图标" v-model="state.ruleForm.meta.icon" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="组件路径" prop="component">
							<el-input v-model="state.ruleForm.component" placeholder="组件路径" clearable></el-input>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="是否外链" prop="meta.iflink">
							<el-radio-group v-model="state.ruleForm.meta.iflink" :disabled="state.ruleForm.meta.iframe" @change="onSelectLinkChange">
								<el-radio :label="true">是</el-radio>
								<el-radio :label="false">否</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="是否iframe" prop="meta.iframe">
							<el-radio-group v-model="state.ruleForm.meta.iframe" :disabled="state.ruleForm.meta.iflink" @change="onSelectIframeChange">
								<el-radio :label="true">是</el-radio>
								<el-radio :label="false">否</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="链接地址" prop="meta.link">
							<el-input
								v-model="state.ruleForm.meta.link"
								placeholder="外链/iframe时链接地址"
								clearable
								:disabled="!(state.ruleForm.meta.iflink || state.ruleForm.meta.iframe)"
							>
							</el-input>
						</el-form-item>
					</el-col>
					<!-- </template> -->

					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="菜单排序" prop="menuSort">
							<el-input-number v-model="state.ruleForm.menuSort" controls-position="right" placeholder="请输入排序" class="w100" />
						</el-form-item>
					</el-col>
					<!-- <template> -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="是否隐藏">
							<el-radio-group v-model="state.ruleForm.meta.hide">
								<el-radio :label="true">隐藏</el-radio>
								<el-radio :label="false">不隐藏</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="页面缓存">
							<el-radio-group v-model="state.ruleForm.meta.keepAlive">
								<el-radio :label="true">缓存</el-radio>
								<el-radio :label="false">不缓存</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="是否固定">
							<el-radio-group v-model="state.ruleForm.meta.affix">
								<el-radio :label="true">固定</el-radio>
								<el-radio :label="false">不固定</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>

					<!-- </template> -->
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(menuDialogFormRef)" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemMenuDialog">
import { defineAsyncComponent, reactive, onMounted, ref, nextTick, computed } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { storeToRefs } from 'pinia';
import { useRoutesList } from '/@/stores/routesList';
import { i18n } from '/@/i18n/index';
import { useMenuApi } from '/@/api/sys/menu';
import msg from '/@/utils/messageUtils';
// import { setBackEndControlRefreshRoutes } from "/@/router/backEnd";

// 定义子组件向父组件传值/事件 定义一个传输事件
const emit = defineEmits(['refresh']);

// 引入组件
const IconSelector = defineAsyncComponent(() => import('/@/components/iconSelector/index.vue'));

// 定义变量内容
const menuDialogFormRef = ref();
const stores = useRoutesList();
const { realTimeRoutesList } = storeToRefs(stores);
// const { routesList } = storeToRefs(stores);
const state = reactive({
	ruleForm: {
		id: 0,
		menuTitle: '',
		menuName: '',
		parentId: '0',
		component: '', // 组件路径
		link: false, // 是否外链
		menuSort: 0, // 菜单排序
		accessPath: '', // 路由路径
		redirect: '', // 路由重定向，有子集 children 时
		meta: {
			title: '', // 菜单名称
			icon: '', // 菜单图标
			hide: false, // 是否隐藏
			keepAlive: true, // 是否缓存
			affix: false, // 是否固定
			link: '', // 外链/内嵌时链接地址（http:xxx.com），开启外链条件，`1、link: 链接地址不为空`
			iframe: false, // 是否内嵌，开启条件，`1、iframe:true 2、link：链接地址不为空`
			iflink: false,
			roles: '', // 权限标识，取角色管理
		},
		btnPower: '', // 菜单类型为按钮时，权限标识
	},
	menuData: [] as RouteItems, // 上级菜单数据
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});

const menuNameRulesMessage: any = computed(() => i18n.global.t('message.sys.rules.menu_name_require'));
const menuTitleRulesMessage: any = computed(() => i18n.global.t('message.sys.rules.menu_name_require'));
const menuPathRulesMessage: any = computed(() => i18n.global.t('message.sys.rules.menu_name_require'));
const menuIconRulesMessage: any = computed(() => i18n.global.t('message.sys.rules.menu_name_require'));

const rules = reactive<FormRules>({
	parentId: [{ required: true, message: '父菜单不能为空', trigger: 'blur' }],
	menuName: [{ required: true, message: menuNameRulesMessage, trigger: 'blur' }],
	menuTitle: [{ required: true, message: '菜单标题不能为空', trigger: 'blur' }],
	'meta.title': [{ required: true, message: menuTitleRulesMessage, trigger: 'blur' }],
	accessPath: [{ required: true, message: menuPathRulesMessage, trigger: 'blur' }],
	'meta.icon': [{ required: true, message: menuIconRulesMessage, trigger: 'blur' }],
});

// 获取 pinia 中的路由
const getMenuData = (routes: RouteItems) => {
	const arr: RouteItems = [];
	routes.map((val: RouteItem) => {
		val['title'] = i18n.global.t(val.meta?.title as string);
		arr.push({ ...val });
		if (val.children) getMenuData(val.children);
	});
	return arr;
};

// 打开弹窗
const openDialog = (type: string, row?: any) => {
	state.menuData = getMenuData(realTimeRoutesList.value);
	if (type === 'edit') {
		state.dialog.title = i18n.global.t('message.sys.menu.update');
		state.dialog.submitTxt = i18n.global.t('message.common.update');
		state.ruleForm.id = row.id;
		viewMenu(row.id);
		nextTick(() => {
			menuDialogFormRef.value.clearValidate();
		});
	} else {
		state.dialog.title = i18n.global.t('message.sys.menu.add');
		state.dialog.submitTxt = i18n.global.t('message.common.add');
		console.log('row: ', row);
		// 清空表单，此项需加表单验证才能使用
		nextTick(() => {
			menuDialogFormRef.value.resetFields();
			menuDialogFormRef.value.clearValidate();
			if (row) {
				state.ruleForm.parentId = row.id;
			}
		});
	}
	state.dialog.type = type;
	state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};

const onSelectLinkChange = () => {
	if (state.ruleForm.meta.iflink) {
		state.ruleForm.meta.iframe = false;
		rules['meta.link'] = [{ required: true, message: '请输入链接地址', trigger: 'blur' }];
	} else {
		delete rules['meta.link'];
	}
};

// 是否内嵌下拉改变
const onSelectIframeChange = () => {
	if (state.ruleForm.meta.iframe) {
		state.ruleForm.meta.iflink = false;
		rules['meta.link'] = [{ required: true, message: '请输入链接地址', trigger: 'blur' }];
	} else {
		delete rules['meta.link'];
	}
};

const viewMenu = async (menuId: string) => {
	try {
		const { data } = await useMenuApi().viewMenu(menuId);
		state.ruleForm = data;
		if (data.meta.link) {
			state.ruleForm.link = true;
		} else {
			state.ruleForm.link = false;
		}
		console.log('菜单: ', JSON.stringify(data));
	} catch (error) {
		msg().error('获取菜单详细信息失败，请重试');
	}
};

// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	// if (state.dialog.type === 'add') {
	// 	menuDialogFormRef.value?.clearValidate(['menuName']);
	// }

	console.log('parentId: ', typeof state.ruleForm.parentId);

	if ('object' == typeof state.ruleForm.parentId) {
		state.ruleForm.parentId = state.ruleForm.parentId[0];
	}

	await formEl.validate(async (valid) => {
		if (valid) {
			try {
				if (state.dialog.type === 'add') {
					await useMenuApi().addMenu(state.ruleForm);
				} else {
					await useMenuApi().updateMenu(state.ruleForm);
				}
				msg().success('success');
				closeDialog(); // 关闭弹窗
				emit('refresh');
			} catch (error: any) {
				msg().error('error');
			}
		}
	});

	// setBackEndControlRefreshRoutes() // 刷新菜单，未进行后端接口测试
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>
